<template>
  <div>
    <el-dialog title="现场咨询" :visible.sync="modalShow" width="60%" :before-close="modalClose" center>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-row type="flex">
          <el-row style="width:50%">
            <div class="top">
              <el-form-item style="width:60%" label="就诊类型" prop="treatType">
                <dictionary-selector code="swan_front_jzlx" :value.sync="ruleForm.treatType" />
              </el-form-item>
              <!-- 选择咨询分类 -->
              <el-form-item style="width:60%" label="主要需求" prop="oneDemand">
                <el-select v-model="ruleForm.oneDemand" placeholder="请选择" @change="changeValue(1,ruleForm.oneDemand)">
                  <el-option v-for="(item,i) of ruleForm.regions" :key="i" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item style="width:60%" label="次需求1" prop="towDemand">
                <el-select v-model="ruleForm.towDemand" placeholder="请选择" @change="changeValue(2,ruleForm.towDemand)">
                  <el-option v-for="(item,i) of ruleForm.regions" :key="i" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item style="width:60%" label="次需求2" prop="threeDemand">
                <el-select v-model="ruleForm.threeDemand" placeholder="请选择" @change="changeValue(3,ruleForm.threeDemand)">
                  <el-option v-for="(item,i) of ruleForm.regions" :key="i" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="意向项目" style="width:80%" prop="intentCaseName">
              <el-input v-model="ruleForm.intentCaseName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="主治医生" style="width:80%" prop="faceDoctorName">
              <el-select v-model="ruleForm.faceDoctorName" placeholder="请选择" @change="changeValue(3,ruleForm.faceDoctorName)">
                <el-option v-for="item of ruleForm.options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="咨询情况" prop="advisoryInfo">
              <ul class="box">
                <li>顾客诉求：<el-input v-model="ruleForm.appeal" /></li>
                <li>顾客情况：<el-input v-model="ruleForm.situation" /></li>
                <li>诊断结果：<el-input v-model="ruleForm.recustomer" /></li>
              </ul>
            </el-form-item>
            <el-form-item label="面诊医生" prop="healthStatus">
              <!-- 点击后，先保存当前咨询记录，然后向主治医生发出面诊任务 -->
              <el-button @click="addConsultation">发起面诊</el-button> {{ interviewTaskDate }}
            </el-form-item>
            <el-form-item label="面诊意见" prop="opinion">
              <div class="box">
                <el-input v-model="ruleForm.opinion" />
              </div>
              <el-button type="text"> 更新 </el-button>
            </el-form-item>
            <el-form-item label="附件说明" prop="attachUrl">
              <el-upload :action="uploadUrl" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="fileRemove" :before-remove="handleRemove" :on-success="handleList">
                <i class="el-icon-plus" />
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <el-form-item label="咨询结果" prop="result">
              <el-radio v-model="ruleForm.result" label="成交">成交</el-radio>
              <el-radio v-model="ruleForm.result" label="未成交">未成交</el-radio>
            </el-form-item>
            <el-form-item v-if="ruleForm.result==='成交'" label="" prop="handPlane">
              <el-button>去开单</el-button>
              <el-button>去充值</el-button>
            </el-form-item>
            <div v-if="ruleForm.result==='未成交'">
              <el-form-item style="width:65%" label="不成交原因" prop="loseReason">
                <dictionary-selector code="swan_front_bcjyy" :value.sync="ruleForm.loseReason" />
              </el-form-item>
              <el-form-item label="原因补充" prop="reasonMsg">
                <div class="box">
                  <el-input v-model="ruleForm.reasonMsg" class="input" />
                </div>
              </el-form-item>
              <el-form-item style="width:65%" label="固定回访" prop="towDemand">
                <el-switch
                  v-model="value"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item style="width:65%" label="回访日期" prop="rebackTime">
                <!-- <el-select v-model="ruleForm.towDemand" placeholder="选择时间" @change="changeValue(2,ruleForm.towDemand)"> -->
                <!-- <el-option :label="value1" :value="value1"> -->
                <el-date-picker
                  v-model="ruleForm.rebackTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd hh:m:mm"
                />
                <!-- </el-option> -->
                <!-- </el-select> -->
              </el-form-item>
              <!-- 回访人默认是自己 -->
              <el-form-item style="width:65%" label="回访人" prop="rebackMan">
                <el-select v-model="ruleForm.rebackMan" placeholder="选择回访人" @change="changeValue(2,ruleForm.rebackMan)">
                  <el-option v-for="item of ruleForm.getAllUsr" :key="item.id" :label="item.usrName" :value="item.id" />
                </el-select>
              </el-form-item>
              <!-- 默认拉取顾客资料里面的电话 -->
              <el-form-item style="width:65%" label="联系电话" prop="customerPhone">
                <el-input v-model="ruleForm.customerPhone" />
              </el-form-item>
            </div>
          </el-row>
          <el-row class="information">
            顾客相关资料
            <el-row type="flex">
              <el-col :span="8">头像</el-col>
              <el-col>
                <div>{{ userInfo.nickname }} （No.{{ userInfo.code }}）</div>
                <div>手机：
                  <span v-if="one">{{ userInfo.phone }}</span>
                  <span v-if="!one">{{ userInfo.hidePhone }}</span>
                  <el-button type="text" @click="one=!one">{{ one?'隐藏':'显示完整' }}</el-button>
                </div>
                <div>身份证：
                  <span v-if="two">{{ userInfo.idNumber }}</span>
                  <span v-if="!two">{{ userInfo.hideIdNumber }}</span>
                  <el-button type="text" @click="two=!two">{{ two?'隐藏':'显示完整' }}</el-button>
                </div>
                <div>余额：{{ userInfo.capital }}</div>
              </el-col>
            </el-row>
            <el-row>
              特征信息
              <el-col>
                生日
                <span>{{ userInfo.birthday }}</span>
              </el-col>
              <el-col>
                年龄
                <span>{{ userInfo.age }}</span>
              </el-col>
              <el-col>
                省市
                <span>{{ userInfo.address }}</span>
              </el-col>
              <el-col>
                区县
                <span>{{ userInfo.address }}</span>
              </el-col>
            </el-row>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title">
                  展开
                  <!-- <i class="el-icon-arrow-right" /> -->
                  <!-- <i class="el-icon-arrow-down" /> -->
                </template>
                <el-col>
                  区县
                  <span>{{ userInfo.address }}</span>
                </el-col>
              </el-collapse-item>
            </el-collapse>
            <el-row>
              归属信息
              <el-col>
                开发渠道
                <span>{{ userInfo.property }}</span>
              </el-col>
              <el-col>
                推荐人
                <span>{{ userInfo.recommenderName }}</span>
              </el-col>
              <el-col>
                开发人员
                <span>{{ userInfo.developersName }}</span>
              </el-col>
              <el-col>
                归属咨询师
                <span>{{ userInfo.attributionConsultantName }}</span>
              </el-col>
            </el-row>
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title">
                  展开
                </template>
                <el-col>
                  区县
                  <span>{{ userInfo.address }}</span>
                </el-col>
              </el-collapse-item>
            </el-collapse>
            <el-row>
              <el-col>咨询记录</el-col>
              <el-col>
                <span>{{ userInfo.phone }}</span>
                <span>现场咨询{{ userInfo.phone }}</span>
                <span>隆鼻{{ userInfo.phone }}</span>
                <span>未成交{{ userInfo.phone }}</span>
                <el-button type="text">查看记录</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col>消费记录</el-col>
              <el-col>
                <span>{{ userInfo.phone }}</span>
                <span>精致综合美鼻{{ userInfo.phone }}</span>
                <span>￥5000{{ userInfo.phone }}</span>
                <el-button type="text">查看记录</el-button>
              </el-col>
            </el-row>
          </el-row>
        </el-row>
        <el-form-item>
          <el-row type="flex" class="buttons">
            <el-col :offset="4">
              <!-- 仅保存，还可以再更改 -->
              <el-button type="primary" plain @click="submitForm('ruleForm',1)">保存</el-button>
            </el-col>
            <el-col>
              <!-- 点击后，当次咨询不可再更改 -->
              <el-button type="primary" plain @click="submitForm('ruleForm',2)">结束咨询</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script>
import { DictionarySelector } from "@rabbit.do/rabbit";
export default {
  name: "Index",
  components: { DictionarySelector },
  props: {
    modalVisibleData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      uploadUrl: window.GLOBAL.FILE_SERVER + "/api/v1/base/attach/data/upload/attach",
      modalShow: false,
      value: true,
      value1: '',
      options: [],
      dialogImageUrl: '',
      dialogVisible: false,
      demandData: [], // 添加咨询时主次需求
      ruleForm: { result: '成交' },
      reasonMsg: '',
      userInfo: {},
      one: false,
      two: false,
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      rules: {
        treatType: [// 就诊类型
          { required: true, message: '请输入原因', trigger: 'blur' },
        ],
        oneDemand: [// 主要需求
          { required: true, message: '请选择主要需求', trigger: 'change' },
        ],
        result: [// 咨询结果
          { required: true, message: '请输入咨询结果', trigger: 'blur' },
        ],
        loseReason: [// 未成交原因
          { required: true, message: '请输入原因', trigger: 'blur' },
        ],
      },
      interviewTaskDate: '',
    };
  },
  watch: {
    modalVisibleData: {
      handler(newRow) {
        this.getCustomer();
        this.fetchDetail(newRow.id);
        console.log(this.modalVisibleData, "88888");
      },
    },
    deep: true,
  },
  // beforeDestroy() {
  //   this.editor.destroy();
  // },
  mounted() {
    this.fetchProduct('doctor/consulting/productList');
    this.fetchHospital();
    this.fetchAllUsr();
    this.getCustomer();
    this.fetchDetail(this.modalVisibleData.id);
  },
  methods: {
    fetchDetail(id) { // 获取订单详情
      this.$api['doctor/consulting/hospitalTriage']({ id }).then(res => {
        if (res.code !== 200) return;
        this.ruleForm = res.data;
        console.log(res, "详情呀呀丫丫丫丫");
      });
    },
    async addConsultation() { // 点击发起面诊interviewTask
      const res = await this.$api['doctor/consulting/interviewTask'](this.ruleForm);
      if (res.code !== 200) return this.$message.error('发起面诊失败！');
      this.$message.success('发起面诊成功');
      this.interviewTaskDate = new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate();
    },
    async getCustomer() { // 查询顾客信息
      // const res = await this.$api['department/order/customer']({ 'id': this.modalVisibleData.customerId });
      const res = await this.$api['department/order/customer']({ 'id': '1336199807848550401' });
      if (res.code !== 200) return this.$message.error('查询顾客信息失败！');
      this.userInfo = res.data;
      this.$set(this.userInfo, 'hidePhone', this.userInfo.phone.slice(0, 3) + '****' + this.userInfo.phone.slice(7, 11));
      this.$set(this.userInfo, 'hideIdNumber', this.userInfo.idNumber.slice(0, 3) + '****' + this.userInfo.idNumber.slice(16, 18));
      console.log(this.userInfo, '查询顾客信息失败！');
    },
    async fetchHospital() { // 获取医生
      const res = await this.$api['doctor/consulting/hisusrjobSelect']({ "hospitalJobName": "主治医生" });
      if (res.code !== 200) return this.$message.error('查询医生失败！');
      this.options = [];
      res.data.forEach((item, i) => {
        this.options[i] = { value: item.id, label: item.usrName };
      });
      console.log(this.options, '565656');
      this.$set(this.ruleForm, 'options', this.options);
    },
    async fetchAllUsr() { // 获取全部医院人员
      const res = await this.$api['doctor/consulting/getAllUsr']({});
      if (res.code !== 200) return this.$message.error('查询人员失败！');
      this.$set(this.ruleForm, 'getAllUsr', res.data);
      console.log(res, "dkfsdjhfdjkfio");
    },
    handleList(response, file, fileList) {
      const list = [];
      fileList.forEach(item => {
        list.push(item.response.data.id);
      });
      this.$message.success('上传成功');
      this.ruleForm.attachUrl = list.join(",");
    },
    fetchProduct(url) {
      this.$api[url]({
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      }).then(res => {
        if (res.code !== 200) return;
        this.$set(this.ruleForm, 'regions', res.data.result);
      });
    },
    changeValue(number, id) {
      const regions = this.ruleForm.regions;
      if (number === 1 && id) {
        this.dataSome(id, number, regions);
      } else if (number === 2 && id) {
        this.dataSome(id, number, regions);
      } else if (number === 3 && id) {
        this.dataSome(id, number, regions);
      }
    },
    dataSome(id, number, regions) {
      let is = 0;
      const bool = this.demandData.some((item, i) => {
        is = i;
        return this.demandData[i].demandSort === number;
      });
      bool ? this.demandData[is] = this.demandDtos(id, regions, number) : this.demandData.push(this.demandDtos(id, regions, number));
    },
    init() {
      this.modalShow = true;
      this.$nextTick(() => {
        console.log(this.$refs[this.$refs.ruleForm], "00909909");
      });
    },
    modalClose() {
      this.modalShow = false;
    },
    submitForm(formName, number) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = '';
          let msg = '';
          if (number === 1) {
            url = 'doctor/consulting/addProduct';
            msg = '保存成功';
          } else {
            url = 'doctor/consulting/addProductEnd';
            msg = '结束咨询成功';
          }
          this.$set(this.ruleForm, 'advisoryInfo', JSON.stringify({ 'appeal': this.ruleForm.appeal, 'situation': this.ruleForm.situation, 'recustomer': this.ruleForm.recustomer }));
          this.$set(this.ruleForm, 'triageId', this.modalVisibleData.id);
          this.$api[url]({
            ...this.modalVisibleData, ...this.ruleForm,
            'demandDtos': this.demandData,
          }).then(res => {
            if (res.code !== 200) return this.$msg.error('新增咨询失败');
            this.$emit('close');
            this.$message.success(msg);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async handleRemove(file, fileList) {
      const id = file.response.data.id;
      const res = await this.$api['doctor/consulting/deleteImage']({ fileId: id });
      if (res.code !== 200) return false;
      this.$message.success('删除成功');
    },
    fileRemove(file, fileList) {
      const list = [];
      fileList.forEach(item => {
        list.push(item.response.data.id);
      });
      this.ruleForm.attachUrl = list.join(",");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    demandDtos(projectId, regions, number) {
      let obj = {};
      regions.forEach(r => {
        if (projectId === r.id) obj = { "demandSort": number, "projectId": r.id, "projectName": r.name };
      });
      return obj;
    },
  },
};

</script>

<style scoped lang="scss">
// .top {
//   display: flex;
// }
// .buttons {
//   padding: 2px 4px !important;
//   height: 32px;
//   margin-left: 10px;
//   background: rgb(81, 204, 194);
//   color: #fff;
// }

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.information{
  line-height: 40px;
}
.buttons{
  button{
    width: 140px;
    height: 40px;
  }
}
.el-collapse-item__header{
  border-bottom: none !important;
}
.el-collapse{
  border-bottom: none;
  border-top: none;
}
.box{
  border: 1px solid #aaaaaa;
  min-height: 90px;
  padding: 5px;
  width: 90%;
  li{
    margin: 0 10px;
  }
}
</style>
